<template>
  <a-tooltip content="消息通知">
    <a-button
      class="nav-btn notice-btn"
      type="outline"
      :shape="'circle'"
      @click="openNoticeModal"
    >
      <template #icon>
        <a-badge :count="unreadCount" :max-count="99">
          <icon-notification :class="{ 'has-unread': unreadCount > 0 }" />
        </a-badge>
      </template>
    </a-button>
  </a-tooltip>
  
  <!-- 通知详情模态框 -->
  <NoticeModal
    v-model:visible="noticeModalVisible"
    @update-count="updateUnreadCount"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import NoticeModal from './NoticeModal.vue'
import { getUnreadCountApi } from '@/api/notice'

const noticeModalVisible = ref(false)
const unreadCount = ref(0)

// 打开通知模态框
const openNoticeModal = () => {
  noticeModalVisible.value = true
}

// 获取未读消息数量
const getUnreadCount = async () => {
  try {
    const response = await getUnreadCountApi()
    if (response.data.code === '00000') {
      unreadCount.value = response.data.data || 0
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error)
  }
}

// 更新未读消息数量
const updateUnreadCount = (count) => {
  unreadCount.value = count
}

// WebSocket消息监听
const handleWebSocketMessage = (message) => {
  if (message.code === 'NOTICE_MESSAGE') {
    // 收到新通知，增加未读数量
    unreadCount.value += 1
    
    // 显示桌面通知
    if (Notification.permission === 'granted') {
      new Notification(message.info.title || '新消息通知', {
        body: message.info.introduce || message.info.messageContent,
        icon: '/favicon.ico'
      })
    }
  }
}

onMounted(() => {
  // 获取初始未读数量
  getUnreadCount()
  
  // 请求桌面通知权限
  if (Notification.permission === 'default') {
    Notification.requestPermission()
  }
})

// 暴露方法供父组件调用
defineExpose({
  updateUnreadCount,
  handleWebSocketMessage
})
</script>

<style scoped>
.notice-btn {
  position: relative;
}

.notice-btn .has-unread {
  color: #f53f3f;
  animation: shake 0.5s;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-2px); }
  75% { transform: translateX(2px); }
}

:deep(.arco-badge-number) {
  font-size: 10px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
}
</style>